#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <sstream>
#include <tuple>
using namespace std;

int dijkstra(vector<vector<vector<int>>> &gh, int s, int sm, int m)
{
        int n = gh.size() - 1;
        vector<vector<int>> vis(n + 1, vector<int>(m + 1, 0));
        vector<int> dis(n + 1, INT32_MAX);
        priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<>> pq;

        dis[s] = 0;
        pq.emplace(0, sm, s);
        while(!pq.empty()){
                auto [k, l, u] = pq.top();
                pq.pop();
                if(vis[u][l]){
                        continue;
                }
                vis[u][l] = 1;
                // if(u == n){
                //         return dis[n];
                // }
                for(auto e : gh[u]){
                        int v = e[0], level = e[1];
                        int hc = (l == level ? 0 : 1);
                        if(!vis[v][level] && k + hc <= dis[v]){
                                dis[v] = k + hc;
                                pq.emplace(dis[v], level, v);
                        }
                }
        }
        return dis[n];
}

int main()
{
	int m, n, sm;
	cin >> m >> n;
	vector<vector<vector<int>>> gh(n + 1);

	for (int i = 0; i <= m; i++) {
		string s;
		getline(cin, s);

                stringstream sin(s);
                int u, v;
                sin >> u;
                while(sin >> v){
                        if(v == 1 || u == 1){
                                sm = i;
                        }
                        gh[u].push_back({v, i});
                        u = v;
                }
	}

        int ans = dijkstra(gh, 1, sm, m);
        if(ans == INT32_MAX){
                cout<<"NO"<<endl;
        }else{
                cout<<ans<<endl;
        }

        return 0;
}